﻿using System;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using IndexMarkSilverlightClient;
using IndexMarkSilverlightClient.Classes;
using System.Windows.Data;
using System.Collections.Generic;
using IndexMarkSilverlightClient.IndexMarkServiceReference;
using System.Collections.ObjectModel;
using IndexMarkSilverlightClient.Classes.Converters;
using SharedCode;

namespace IndexMarkSilverlightClient.Views
{
    public partial class RespAnswersWindow : ChildWindow
    {
        private RespAnswersViewModel viewModel = null;

        public RespAnswersViewModel ViewModel
        {
            get 
            { 
                return viewModel; 
            }
        }
        
        public RespAnswersWindow()
        {
            InitializeComponent();
            viewModel = Resources["RespAnswersViewModel"] as RespAnswersViewModel;
            viewModel.LoadCompleted += new ViewModelBase.LoadEventHandler(viewModel_LoadCompleted);
            viewModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(viewModel_PropertyChanged);
            Loaded += new RoutedEventHandler(RespAnswersWindow_Loaded);
        }

        void viewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "RespAnswers")
            {
                VolumeTable.ItemsSource = null;
                VolumeTable.ItemsSource = viewModel.RespAnswers.Answers;
                viewModel.OrderedAnswers();
            }
        }

        void viewModel_LoadCompleted(object sender, LoadEventArgs e)
        {
            if (e.Type == typeof(bool))
            {
                DialogResult = true;
            }
        }

        void RespAnswersWindow_Loaded(object sender, RoutedEventArgs e)
        {
            viewModel.LoadAnswers();
        }

        private void SetOpacityControls(double O, bool Enabled)
        {
            foreach (UIElement ctrl in this.LayoutRoot.Children)
            {
                ctrl.Opacity = O;
            }
            
            VolumeTable.IsEnabled = Enabled;
            Add.IsEnabled = Enabled;
            Update.IsEnabled = Enabled;
            Delete.IsEnabled = Enabled;
            OKButton.IsEnabled = Enabled;
            CancelButton.IsEnabled = Enabled;
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            loadBar.Visibility = Visibility.Visible;
            SetOpacityControls(0.6, false);
            viewModel.SaveAnswers();
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }

        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            DeleteAnswer();
        }

        private void Add_Click(object sender, RoutedEventArgs e)
        {
            AddAnswerWindow win = new AddAnswerWindow();
            win.viewModel.CurrentChar = viewModel.CurrentChar;
            win.viewModel.CurrentTerm = viewModel.CurrentTerm;
            win.Title += " для " + viewModel.RespAnswers.Resp.ShortName;
            win.Show();
            win.Closing += new EventHandler<System.ComponentModel.CancelEventArgs>(win_Closing);
        }

        void win_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if ((sender as AddAnswerWindow).DialogResult == true)
            {
                Answer A = (sender as AddAnswerWindow).viewModel.Answer;
                viewModel.AddAnswer(A);
            }
        }

        private void VolumeTable_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            if ((e.Row.DataContext as Answer).State == StateObject.Deleted)
            {
                e.Row.Visibility = Visibility.Collapsed;
            }
            
            //for (int i = 0; i < viewModel.RespAnswers.Answers.Count; i++)
            //{
            //    if (viewModel.RespAnswers.Answers[i].Fishily)
            //    {
            //        e.Row.Background = new SolidColorBrush(Color.FromArgb(100, 255, 50, 50));
            //    }
            //    else
            //    {
            //        e.Row.Background = new SolidColorBrush(Color.FromArgb(100, 255, 255, 255));
            //    }
            //}
        }

        private void VolumeTable_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                DeleteAnswer();
            }
        }

        private void DeleteAnswer()
        {
            //if (MessageBox.Show("Вы действительно хотите удалить выделенные записи?", "Внимание", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            //{
                viewModel.DeleteAnswers();
            //}
        }

        private void Update_Click(object sender, RoutedEventArgs e)
        {
            AddAnswerWindow AW = new AddAnswerWindow();
            AW.viewModel.CurrentChar = viewModel.CurrentChar;
            AW.viewModel.CurrentTerm = viewModel.CurrentTerm;
            AW.viewModel.Answer = viewModel.AnswerForEdit;
            AW.Title = "Редактирование показателя для " + viewModel.RespAnswers.Resp.ShortName;
            AW.isUpdated = true;
            AW.Closed += new EventHandler(AW_Closed);
            AW.Show();
        }

        void AW_Closed(object sender, EventArgs e)
        {
            viewModel.AnswerForEdit = (sender as AddAnswerWindow).viewModel.Answer;
            //viewModel.OrderedAnswers();
            //VolumeTable.ItemsSource = null;
            //VolumeTable.ItemsSource = viewModel.RespAnswers.Answers;
        }

        private void commonCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            viewModel.SelectAnswers(true);
        }

        private void commonCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            viewModel.SelectAnswers(false);
        }

        private void TextBlock_Loaded(object sender, RoutedEventArgs e)
        {
            //делаем привязку к свойству Volume
            Binding binding = new Binding("Text");
            binding.Converter = new AnswerToVolumeConverter();
            binding.Path = new PropertyPath("Volume");
            binding.ConverterParameter = viewModel.CurrentChar;
            (sender as TextBlock).SetBinding(TextBlock.TextProperty, binding);
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            viewModel.SelectAnswer((sender as CheckBox).DataContext as Answer, true);
        }

        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            viewModel.SelectAnswer((sender as CheckBox).DataContext as Answer, false);
        }

        public CheckBox GetCheckBoxWithParent(UIElement parent, Type targetType, string ElementName)
        {
            if (parent.GetType() == targetType && ((CheckBox)parent).Name == ElementName)
            {
                return (CheckBox)parent;
            }
            CheckBox result = null;
            int count = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < count; i++)
            {
                UIElement child = (UIElement)VisualTreeHelper.GetChild(parent, i);

                if (GetCheckBoxWithParent(child, targetType, ElementName) != null)
                {
                    result = GetCheckBoxWithParent(child, targetType, ElementName);
                    break;
                }
            }
            return result;
        }

    }
}

